﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace CommHelper
{
    /// <summary>
    /// 解决Console.Write写大量字符串异常
    /// </summary>
    public sealed class ConsoleHelper
    {
        public static IntPtr OutHandle
        {
            get
            {
                if (outHandle == IntPtr.Zero)
                    outHandle = GetStdHandle(StdHandle.STD_OUTPUT_HANDLE);
                return outHandle;
            }
        }

        public static void Write(string value)
        {
            if (OutHandle == IntPtr.Zero)
                return;
            int numberOfCharsWritten;
            char[] valueArray = value.ToCharArray();
            WriteConsole(outHandle, valueArray, System.Text.Encoding.GetEncoding("GB2312").GetBytes(value).Length, out numberOfCharsWritten, 0);
        }

        public static void Write(string format, params Object[] arg)
        {
            Write(string.Format(format, arg));
        }

        public static void WriteLine(string value)
        {
            Write(value + Environment.NewLine);
        }

        public static void WriteLine(string format, params Object[] arg)
        {
            Write(format + Environment.NewLine, arg);
        }

        enum StdHandle
        {
            STD_INPUT_HANDLE = -10,
            STD_OUTPUT_HANDLE = -11,
            STD_ERROR_HANDLE = -12
        }

        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        static extern IntPtr GetStdHandle(StdHandle nStdHandle);

        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        static extern int WriteConsole(
                IntPtr hConsoleOutput,
                char[] lpBuffer,
                int nNumberOfCharsToWrite,
                out int lpNumberOfCharsWritten,
                int lpReserved
        );

        static IntPtr outHandle = IntPtr.Zero;
    }
}
